package lifeimprint.BluetoothSample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Activity01 extends Activity{
    /** Called when the activity is first created. */
	private BluetoothAdapter btadapter=null;
	private BtDiscoverReceiver myReceiver=null;
	private ReceiverGPSInfo gpsReceiver=null;
	private IntentFilter myIntentFilter=null;
	private IntentFilter GPSIntentFilter=null;
	private ArrayList<BluetoothDevice>myDevices=null;
	private BluetoothDevice gpsdevices=null;
	private BluetoothSocket mysocket=null;
	private Button startbutton=null;
	private Button stopbutton=null;
	private Button scanbutton=null;
	private Button connectbutton=null;
	private Button stopconnectbutton=null;
	private TextView gpsinfotext=null;
	private LocationManager locationManager=null;
	private LocationListener Textlistener=null;
	
	private Mythread upthread=null;
	private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
	private static final float KM_Factor=1.852f;
	private static String gpsaddress = "00:02:76:C9:AE:AF";
	
	String mocLocationProvider =LocationManager.GPS_PROVIDER;
	//String mocLocationProvider ="text";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btadapter=BluetoothAdapter.getDefaultAdapter();
        startbutton=(Button)findViewById(R.id.startbutton);
        stopbutton=(Button)findViewById(R.id.stopbutton);
        scanbutton=(Button)findViewById(R.id.scanbutton);
        connectbutton=(Button)findViewById(R.id.connectbutton);
        stopconnectbutton=(Button)findViewById(R.id.stopconnectbutton);
        gpsinfotext=(TextView)findViewById(R.id.gpsinfotext);
        myReceiver=new BtDiscoverReceiver(myDevices);
        gpsReceiver=new ReceiverGPSInfo();
        myIntentFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
        GPSIntentFilter=new IntentFilter(BTGpsService.GPSINFOINFO);
        startbutton.setOnClickListener(new ButtonListener());
        stopbutton.setOnClickListener(new ButtonListener());
        scanbutton.setOnClickListener(new ButtonListener());
        connectbutton.setOnClickListener(new ButtonListener());
        stopconnectbutton.setOnClickListener(new ButtonListener());
        Log.d("mydebug", "onCreate");
        locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.addTestProvider(mocLocationProvider, false, false,false, false, true, true, true, 0, 5);
        locationManager.setTestProviderEnabled(mocLocationProvider, true);
        locationManager.setTestProviderStatus(mocLocationProvider, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
        Textlistener=new myLocationListener();
        locationManager.requestLocationUpdates(mocLocationProvider, 0, 0, Textlistener);
        Log.d("mydebug", Thread.currentThread().getName()+":"+Thread.currentThread().getId());
        
        Activity01.this.registerReceiver(myReceiver, myIntentFilter);
		Activity01.this.registerReceiver(gpsReceiver, GPSIntentFilter);
    }
    
    
    @Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
    	Log.d("mydebug", "onConfigurationChanged");
		super.onConfigurationChanged(newConfig);
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		locationManager.clearTestProviderEnabled(mocLocationProvider);
		locationManager.clearTestProviderStatus(mocLocationProvider);
		locationManager.removeUpdates(Textlistener);
		Activity01.this.unregisterReceiver(gpsReceiver);
		Activity01.this.unregisterReceiver(myReceiver);
		Log.d("mydebug", "Activity onDestroy()");
		super.onDestroy();
		
		
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.d("mydebug", "Activity onPause()");
		super.onPause();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.d("mydebug", "Activity onResume()");
		super.onResume();
		
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		Log.d("mydebug", "Activity onStart()");
		super.onStart();
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		Log.d("mydebug", "Activity onStop()");
		super.onStop();
		//Activity01.this.unregisterReceiver(new ReceiverGPSInfo());
		//rthread.stop();
	}


	private class ButtonListener implements OnClickListener{

		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch(v.getId())
			{
			case R.id.startbutton:{
				try{
					dostart();
					
				}catch (IOException e){
					e.printStackTrace();
				}
				break;
			}
			case R.id.stopbutton:{
				try{
					dostop();
				}catch (IOException e){
					e.printStackTrace();
				}
				break;
			}
			case R.id.scanbutton:{
				try{
					doscan();
					
				}catch (IOException e){
					e.printStackTrace();
				}
				break;
			}
			case R.id.connectbutton:{
				try{
					doconnect();
					
				}catch (IOException e){
					e.printStackTrace();
				}
				break;
			}
			case R.id.stopconnectbutton:{
				try{
					stopdoconnect();
					
				}catch (IOException e){
					e.printStackTrace();
				}
				break;
			}
			}
			/*
			if(btadapter!=null){
				Log.d("mydebug", "Have bluetooth");
				if(!btadapter.isEnabled()){
					Intent btintent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
					startActivity(btintent);
				}
				Set<BluetoothDevice> btdevices=btadapter.getBondedDevices();
				if(btdevices.size()>0){
					for(Iterator iterator=btdevices.iterator();iterator.hasNext();){
						BluetoothDevice bluetoothdevice =(BluetoothDevice)iterator.next();
						Log.d("mydebug",bluetoothdevice.getAddress());
						Log.d("mydebug",bluetoothdevice.getName());
					}
				}
				
			}
			else{
				Log.d("mydebug", "No BlueTooth");
			}*/
		}
	}

		private void stopdoconnect() throws IOException {
			// TODO Auto-generated method stub
			/*if(upthread!=null){
			upthread.ReceiverStopInfo("1");}*/
			Intent serverintent=new Intent();
			serverintent.setClass(Activity01.this, BTGpsService.class);
			this.stopService(serverintent);
		}

		private void doconnect() throws IOException{
			// TODO Auto-generated method stub
			if(btadapter.isEnabled()){
				/*
				gpsdevices=btadapter.getRemoteDevice(gpsaddress);
				Log.d("mydebug","getRemoteDevice gpsaddress:"+gpsaddress);
				mysocket=gpsdevices.createRfcommSocketToServiceRecord(MY_UUID);
				mysocket.connect();
				Log.d("mydebug", Thread.currentThread().getName()+":"+Thread.currentThread().getId());
				upthread=new Mythread();
				upthread.start();
				*/
				Intent serverintent=new Intent();
				serverintent.setClass(Activity01.this, BTGpsService.class);
				this.startService(serverintent);
			}
		}

		private void dostop() throws IOException{
			// TODO Auto-generated method stub
			if(btadapter.isEnabled()){

				btadapter.disable();
				Log.d("mydebug","Stop Bluetooth");
	    		//Activity01.this.finish();
	    	    }

		}

		private void doscan() throws IOException {
			// TODO Auto-generated method stub
			if(!btadapter.isEnabled()){
	    		  Log.d("mydebug","Bluetooth Server not running");
	    	    }
			else{
				//btadapter.startDiscovery();
				Log.d("mydebug","Doing Start Bluetooth Discovery");
			}
		}
    
    
        private void dostart() throws IOException{
    	    if(btadapter==null){
    		  Log.d("mydebug","No BlueTooth");
    	    }
    	    else{
    	    btenable();
    	 	Log.d("mydebug","Finish Bluetooth Enable Intent");
    	
    	 	/*
    	 	while(btadapter.isDiscovering()){
    	 		try{
    	 			Thread.sleep(100);
    	 			Log.d("mydebug","BlueTooth Found A device");
    	 		}
    	 		catch(InterruptedException e){
    	 			e.printStackTrace();
    	 		}
    	 	}*/
    	 	
    	 	//BluetoothDevice mydevice=this.myDevices.get(0);
    	 	//BluetoothSocket mysocket=mydevice.createRfcommSocketToServiceRecord(MY_UUID);
    	 	
    	 	
    	   }
    }
    /*
    private void btDiscover() {
		// TODO Auto-generated method stub
		if(btadapter.getScanMode()==BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
			Intent btenableintent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			btenableintent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
			startActivity(btenableintent);
			Log.d("mydebug","finish bluetoothDiscover");
		}
	}
    */
	private void btenable(){
    	if(!btadapter.isEnabled()){
    		//Intent btenableintent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    		//startActivity(btenableintent);
    		btadapter.enable();
    		Log.d("mydebug","Bluetooth Enable Intent");
    	}
    }
	
	private class handlerthread extends Thread{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Looper mainlooper=Looper.getMainLooper();
			Myhandler mainhandler=new Myhandler(mainlooper);
			super.run();
		}
		
	}
	
    
	private class Mythread extends Thread{
		private String stop=null;
		private InputStream is=null;
		private String line=null;
		private String out=null;
		private Bundle gpsbundle=null;

		public void ReceiverStopInfo(String sstop){
	    	stop=sstop;
	    }
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Looper mainlooper=Looper.getMainLooper();
			Myhandler mainhandler=new Myhandler(mainlooper);
			mainhandler.removeMessages(0);
			
			stop="0";
			//int i=0;
			gpsbundle=new Bundle();
			
			Log.d("mydebug", Thread.currentThread().getName()+":"+Thread.currentThread().getId());
			
			try {
				is = mysocket.getInputStream();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			BufferedReader br=new BufferedReader(new InputStreamReader(is));
			try {
				while((line=br.readLine())!=null){
					if(stop.equals("0")){
						Log.d("mydebug", line);
						HandlingGPS hg=new HandlingGPS(line,"$GPRMC");
						gpsbundle=hg.outputgps();
						if(!gpsbundle.isEmpty()){
							Message m = mainhandler.obtainMessage();
							m.setData(gpsbundle);
							m.sendToTarget();
						}
						}
					else{
						break;
					}
				}
				//Log.d("mydebug", stop);
				br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			super.run();
		}
		
	}
	
	public class Myhandler extends Handler{
		public Myhandler(Looper looper){
            super (looper);
     }
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Bundle b=msg.getData();
			Location location = new Location(mocLocationProvider);
			if(b.getString("0").equals("$GPRMC")){
				if(b.getString("2").equals("V")){
					gpsinfotext.setText("NO GPS");
				}
				else if(b.getString("2").equals("A")){
					
					String LatString=b.getString("3");
					String LonString=b.getString("5");
					String speed_str=b.getString("7");
					String bear_str=b.getString("8");
					
					double Latdu=Double.parseDouble(LatString.substring(0, 2));
					double Latfeng=Double.parseDouble(LatString.substring(2));
					//Log.d("mydebug","latdu:"+Latdu+"LATFENG:"+Latfeng);
					double lat=Latdu+Latfeng/60;
					
					double Londu=Double.parseDouble(LonString.substring(0, 3));
					double Lonfeng=Double.parseDouble(LonString.substring(3));
					double lon=Londu+Lonfeng/60;
					
					float speed=(((Float.parseFloat(speed_str))*KM_Factor)*1000f)/3600f;
					float bear=Float.parseFloat(bear_str);
					
					location.setTime(System.currentTimeMillis());
					location.setLatitude(lat);
					location.setLongitude(lon);
					location.setSpeed(speed);
					location.setBearing(bear);
					Log.d("mydebug", location.toString());
					gpsinfotext.setText("Latitude:"+b.getString("4")+":"+lat+"\n"+"Longitude:"+b.getString("6")+":"+lon+"\n"+"Speed:"+speed+"\n"+"Bear:"+bear);
				}
			}
			
			locationManager.setTestProviderLocation(mocLocationProvider, location);
			
			//gpsinfotext.setText(msg.obj.toString());
			super.handleMessage(msg);
		}
		
		
	}
	
	public class myLocationListener implements LocationListener{

		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			Log.d("mydebug","onLocationChanged");
		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			Log.d("mydebug","onProviderDisabled");
		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			Log.d("mydebug","onProviderEnabled");
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			Log.d("mydebug","onStatusChanged");
		}
		
	}
	
	public class ReceiverGPSInfo extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Bundle b=intent.getExtras();
			Location location = new Location(mocLocationProvider);
			if(b.getString("0").equals("$GPRMC")){
				if(b.getString("2").equals("V")){
					gpsinfotext.setText("NO GPS");
				}
				else if(b.getString("2").equals("A")){
					
					String LatString=b.getString("3");
					String LonString=b.getString("5");
					String speed_str=b.getString("7");
					String bear_str=b.getString("8");
					
					double Latdu=Double.parseDouble(LatString.substring(0, 2));
					double Latfeng=Double.parseDouble(LatString.substring(2));
					//Log.d("mydebug","latdu:"+Latdu+"LATFENG:"+Latfeng);
					double lat=Latdu+Latfeng/60;
					
					double Londu=Double.parseDouble(LonString.substring(0, 3));
					double Lonfeng=Double.parseDouble(LonString.substring(3));
					double lon=Londu+Lonfeng/60;
					
					float speed=(((Float.parseFloat(speed_str))*KM_Factor)*1000f)/3600f;
					float bear=Float.parseFloat(bear_str);
					
					location.setTime(System.currentTimeMillis());
					location.setLatitude(lat);
					location.setLongitude(lon);
					location.setSpeed(speed);
					location.setBearing(bear);
					Log.d("mydebug", location.toString());
					gpsinfotext.setText("Latitude:"+b.getString("4")+":"+lat+"\n"+"Longitude:"+b.getString("6")+":"+lon+"\n"+"Speed:"+speed+"\n"+"Bear:"+bear);
				}
			}
			
			locationManager.setTestProviderLocation(mocLocationProvider, location);
			
		}
		
	}
	
	
}